<template>
  <div class="app-container">
    <el-row>
      <el-col :span="6">
        <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="" prop="searchValue">
            <el-input
              v-model="queryParams.searchValue"
              placeholder="搜索内容"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>



        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              size="mini"
              @click="handleInit"
            >
              <svg-icon icon-class="init" />
              初始化</el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button-->
<!--              type="danger"-->
<!--              plain-->
<!--              icon="el-icon-delete"-->
<!--              size="mini"-->
<!--              :disabled="multiple"-->
<!--              @click="handleDelete"-->
<!--            >删除</el-button>-->
<!--          </el-col>-->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="6">
        <!--        :height="tableHeight"-->
        <el-table ref="mainTableRef" :height="tableHeight" :show-header="false" v-loading="loading" :data="mainList" @selection-change="handleSelectionChange" highlight-current-row @current-change="handleCurrentChange">
<!--          <el-table-column type="selection" width="55" align="center" />-->
          <el-table-column width="30">
            <template slot-scope="scope">
              <img v-if="formatProviderLogo(scope.row)"
                   style="width:30px;height:30px;border-radius: 8px;"
                   :src="formatProviderLogo(scope.row)" >
              </img>
            </template>
          </el-table-column>
          <!--      <el-table-column label="ID" width="55" align="center" prop="id" />-->
          <!--      <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true" />-->
          <el-table-column label="描述" align="left" prop="description" :show-overflow-tooltip="true"/>
          <el-table-column label="状态" align="center" prop="status" width="20">
            <template slot-scope="scope">
              <dict-tag size="mini" :options="dicts.baseEnumEnabledDisabledOptions" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
            <template slot-scope="scope">
              <el-tooltip effect="light" content="查看" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleInfo(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip effect="light"  content="修改" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleEdit(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip  effect="light" content="删除" placement="top">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="18">
        <el-row :gutter="10" class="mb8" style="padding-left: 5px;">
          <el-col :span="1.5">
            <el-button
              :disabled="modelTable.loading"
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAddAiModel"
            >新增</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="modelTable.showSearch" @queryTable="resetModelTable()"></right-toolbar>
        </el-row>
        <el-table v-loading="modelTable.loading" :data="modelTable.list" >
          <el-table-column label="模型名称" align="center" prop="model_name" :show-overflow-tooltip="true" />
          <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
          <el-table-column label="分组" align="center" prop="model_group" :show-overflow-tooltip="true" />
          <el-table-column label="类型" align="center" prop="type">
            <template slot-scope="scope">
              <dict-tag :options="dicts.aiModelTypeOptions" :value="scope.row.type"/>
            </template>
          </el-table-column>
          <el-table-column label="支持工具" align="center" prop="has_tool">
            <template slot-scope="scope">
              <dict-tag :options="dicts.baseEnumYesNoOptions" :value="scope.row.has_tool"/>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :options="dicts.baseEnumEnabledDisabledOptions" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleInfoAiModel(scope.row)"
              ></el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleEditAiModel(scope.row)"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteAiModel(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-col>
    </el-row>

    <AddAIApiDialog ref="AddAIApiDialogRef"></AddAIApiDialog>
    <AddAIModelDialog ref="AddAIModelDialogRef"></AddAIModelDialog>
  </div>
</template>

<script>
import {
  delAIApi, delAIModel,
  initAIApi,
  listAIApi,
  listAIModel
} from '@/api/ai'
import AddAIApiDialog from '@/views/ai-api/add-ai-api-dialog.vue'
import AddAIModelDialog from '@/views/ai-api/add-ai-model-dialog.vue'
import { AI_API_ID_LINK, AI_APIS, AI_PROVIDER } from '@/utils/cherry_studio/llm'
import { mergeFromObject, numberIsZeroOrNull, strIsEmpty } from 'sks-plugin-el-erp/lib/core'
import { sksPageMixin } from 'sks-plugin-el-erp/lib/sks-page'
import { newSksTable } from 'sks-plugin-el-erp/lib/sks-model-utils'
import { getProviderLogo } from '@/utils/cherry_studio/cherry_studio'

export default {
  name: "AIApiIndex",
  components:{
    AddAIApiDialog,
    AddAIModelDialog,
  },
  mixins: [
    // sksPageMixin,
  ],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 日志列表数据
      mainList: [],
      currentRow: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 9999,
        group: undefined,
        chat_id: undefined,
        searchValue: undefined,
      },
      // 详情对话框可见性
      detailVisible: false,
      // 当前查看的日志详情数据
      form: {},

      aiAgentGroupOptions: [],

      modelTable: mergeFromObject(newSksTable(),{
        queryParams:{
          pageNum: 1,
          pageSize: 9999,
          ai_api_id: undefined,
        },
      })
    };
  },
  created() {
    this.getList();
  },
  computed: {
    tableHeight() {
      return window.innerHeight - 250; // 计算表格高度
    }
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      this.currentRow={}
      listAIApi(this.queryParams).then(response => {
        this.mainList = response.rows;
        this.total = response.total;
        this.loading = false;
        if( response.rows.length>0){
          this.$refs.mainTableRef.setCurrentRow(response.rows[0]);
        }
      }).catch(e => {
        this.mainList = [];
        this.loading = false;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    handleAdd({data,title='新增'}={}){
      this.$refs.AddAIApiDialogRef.show({
        form:this.sksUtils.mergeFromObject({},data,{
          payMode: 1,
          is_system: this.dicts.baseEnumConstants.NO,
          status: this.dicts.baseEnumConstants.ENABLED,
          virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.add,

        }),
        dialogInfo:{
          title: title,
          submitCallbackSuccess:({resData}={})=>{
            this.getList()
          },
        }
      })
    },
    handleEdit(row){
      this.$refs.AddAIApiDialogRef.showByUniqueId({
        uniqueId: row.id,
        dialogInfo: {
          title: '修改',
          submitCallbackSuccess:({resData}={})=>{
            this.getList()
          },
        },
        virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.modify,
      })
    },
    handleInfo(row){
      this.$refs.AddAIApiDialogRef.showByUniqueId({
        uniqueId: row.id,
        dialogInfo: {
          title: '查看'
        },
        virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.none,
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(() => {
        return delAIApi(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 复制代码成功 */
    clipboardSuccess() {
      this.$modal.msgSuccess("复制成功");
    },
    initCreateId(){
      let _id=1
      const nameIdMap={}
      for (let name in AI_PROVIDER) {
        nameIdMap[name]=_id
        _id++
      }
      console.log(JSON.stringify(nameIdMap))
    },
    handleInit(){
      // this.initCreateId()
      // return
      // console.log(AI_APIS)
      // console.log(JSON.stringify(AI_APIS))
      const providers=AI_APIS.providers
      const data=[]
      for (let item of providers) {
        const models=[]
        let _id=AI_API_ID_LINK[item.id]
        let description=AI_PROVIDER[item.id]
        if(strIsEmpty(description)||numberIsZeroOrNull(_id)){
          this.$message.error({
            message: `${item.id} 找不到对应的ID(${_id})或描述(${description})`,
            showClose: true,
            duration: 0
          })
          return
        }

        for(let model of item.models){
          models.push({
            name: model.id,
            description: model.name,
            group: model.group,
            type: this.dicts.aiModelTypeEnum.LLAMA_INDEX,
          })
        }

        data.push({
          id: _id,
          name: item.id,
          description: description,
          api_base: item.apiHost,
          api_key: item.apiKey,
          type: item.type,
          models: models,
        })
      }

      this.$modal.confirm('是否初始化？').then(() => {
        return initAIApi(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("初始化成功");
      }).catch(() => { });
    },
    resetModelTable(){
      this.modelTable.list=[]
      this.modelTable.total=0
      this.modelTable.loading=true
      if(!this.currentRow.id){
        return
      }
      let queryParams = this.modelTable.queryParams
      queryParams.ai_api_id=this.currentRow.id
      listAIModel(queryParams).then(res=>{
        console.log("res=",res)
        this.sksUtils.setSksTableDataByPage(this.modelTable,res)
      })
    },
    handleCurrentChange(row){
      this.currentRow=row
      this.resetModelTable()
    },
    formatProviderLogo(row){
      let providerLogo = getProviderLogo(row.name)
      // console.log('providerLogo')
      // console.log(providerLogo)
      return providerLogo
    },

    handleAddAiModel({data,title='新增'}={}){
      this.$refs.AddAIModelDialogRef.show({
        form:this.sksUtils.mergeFromObject({},data,{
          status: this.dicts.baseEnumConstants.ENABLED,
          ai_api_id: this.currentRow.id,
          virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.add,

        }),
        dialogInfo:{
          title: title,
          submitCallbackSuccess:({resData}={})=>{
            this.resetModelTable();
          },
        }
      })
    },
    handleEditAiModel(row){
      this.$refs.AddAIModelDialogRef.showByUniqueId({
        uniqueId: row.id,
        dialogInfo: {
          title: '修改',
          submitCallbackSuccess:({resData}={})=>{
            this.resetModelTable();
          },
        },
        virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.modify,
      })
    },
    handleInfoAiModel(row){
      this.$refs.AddAIModelDialogRef.showByUniqueId({
        uniqueId: row.id,
        dialogInfo: {
          title: '查看'
        },
        virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.none,
      })
    },
    /** 删除按钮操作 */
    handleDeleteAiModel(row) {
      const ids = row.id ? [row.id] : this.ids;
      this.$modal.confirm('是否确认删除编号为"' + ids + '"的数据项？').then(() => {
        return delAIModel(ids);
      }).then(() => {
        this.resetModelTable();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
  }
};
</script>

<style scoped>
</style>
